import java.net.*;
import java.io.*;
import java.awt.*;
import java.util.*;

public class clienteObservador extends Frame implements Runnable{
      protected DataInputStream i;
	  protected DataOutputStream o;
	  protected TextArea output;
	  protected TextField input;
	  protected Thread listener;
	 

	  public void run() {
			try {
			      while (true) {
			    	
			        String line = i.readUTF ();
			        output.append(line + "\n");
			        
			        if(line.equals("carta")){
			        	System.out.print("No recibo cartas, soy un OBSERVADOR"+"\n");
			        }
			        
			        if(line.equals("pregunta")){
			        	System.out.print("hizo una pregunta"+"\n");
			        }
			        
			        if(line.equals("final")){
			        	System.out.print("No recibo cartas, soy un OBSERVADOR"+"\n");
			        	
			        }
			        
			        
			      }
			    } catch (IOException ex) {
			      ex.printStackTrace ();
			    } finally {
			      listener = null;
			      input.hide ();
			      validate ();
			      try {
			        o.close ();
			      } catch (IOException ex) {
			        ex.printStackTrace ();
			      }
			    }
			
		}

    
    
    public clienteObservador (String title, InputStream i, OutputStream o) {
	    super (title);
	    this.i = new DataInputStream (new BufferedInputStream (i));
	    this.o = new DataOutputStream (new BufferedOutputStream (o));
	    setLayout (new BorderLayout ());
	    add ("Center", output = new TextArea ());
	    output.setEditable (false);
	    add ("South", input = new TextField ());
	    pack ();
	    show ();
	    input.requestFocus ();
	    listener = new Thread (this);
	    listener.start ();
	  }
	
	
	public boolean handleEvent (Event e) {
	    if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
	      try {
	        o.writeUTF ((String) e.arg);
	            o.flush (); 
	      } catch (IOException ex) {
	        ex.printStackTrace();
	        listener.stop ();
	      }
	      input.setText ("");
	      return true;
	    } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
	      if (listener != null)
	        listener.stop ();
	      hide ();
	      return true;
	    }
	    return super.handleEvent (e);
	  }
	
	public static void main (String args[]) throws IOException {

		
	    Socket s = new Socket ("localhost", 6000);
	    new clienteprueba ("Black Jack Observador",
	                    s.getInputStream (), s.getOutputStream ());
	    
	  }
	
}
